package ar.org.cfired.creditos.gui.action;

import java.math.BigInteger;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;

import org.jbpm.api.Execution;
import org.jbpm.api.ProcessEngine;
import org.jbpm.api.ExecutionService;
import org.jbpm.api.ProcessInstance;

import ar.org.cfired.creditos.Observaciones;
import ar.org.cfired.creditos.gui.ContenedorObservaciones;
import ar.org.cfired.creditos.gui.Sesion;
import ar.org.cfired.creditos.parametros.EstadosLog;
import ar.org.cfired.creditos.parametros.GuardarParametrosException;
import ar.org.cfired.hibernate.utils.HibernateUtil;

public class ModificarAction extends Action {
	private ExecutionService executionService;
	private ProcessEngine processEngine;

	@Override
	public void execute(Sesion sesion) throws GuardarParametrosException {
		Session hibSession = null;
		
		try {
			hibSession = HibernateUtil.getSessionFactory().getCurrentSession();		
			hibSession.beginTransaction();
			
			EstadosLog estado = new EstadosLog();
				estado.setLogTask(BigInteger.valueOf(Integer.valueOf(sesion.getTareaActiva().getTaskID()).longValue()));
				estado.setLogUsuario(sesion.getUsuario());
				estado.setLogExecutionId((sesion.getTareaActiva().getExecutionID()==null?"a":sesion.getTareaActiva().getExecutionID()));
				estado.setEstId("MO");
			hibSession.save(estado);
			hibSession.getTransaction().commit();
		}
		catch (HibernateException e) {
			if (hibSession.getTransaction() != null)
				if (hibSession.getTransaction().isActive())
					hibSession.getTransaction().rollback();
			e.printStackTrace();
			throw new GuardarParametrosException(); 
		}
		catch (Exception e) {
			if (hibSession.getTransaction() != null)
				if (hibSession.getTransaction().isActive())
					hibSession.getTransaction().rollback();
			e.printStackTrace();
			throw new GuardarParametrosException();
		}		
	}

	@Override
	public void execute(String taskID, String usuario, String executionID)
			throws GuardarParametrosException {
		Session hibSession = null;
		try {
			hibSession = HibernateUtil.getSessionFactory().getCurrentSession();		
			hibSession.beginTransaction();
			
			String instance = executionID.substring(executionID.indexOf(".")+1);
			if (instance.contains("."))
			instance = instance.substring(0,instance.indexOf("."));
			
			EstadosLog estado = new EstadosLog();
				estado.setLogTask(BigInteger.valueOf(Integer.valueOf(taskID).longValue()));
				estado.setLogUsuario(usuario);
				estado.setLogExecutionId((executionID.equals("")?"a":executionID));
				estado.setEstId("MO");
				estado.setLogInstance(BigInteger.valueOf(Integer.valueOf(instance).longValue()));
			hibSession.save(estado);
			
			
			
			Map<String, Object> variables = executionService.getVariables(executionID, executionService.getVariableNames(executionID));
			variables.put("usuarioModificacion", "vvaldes");
			variables.put("executionID", executionID);
			
			ProcessInstance modificacion = executionService.startProcessInstanceByKey("Modificaciones2", variables);			
			//Execution executionHijo = modificacion.getProcessInstance();
			String exId = modificacion.getId();
			
			//for(int i = 0; i<=20;i++){
			/*	SEBA */
			/*	nunca se termino el copiado de las observaciones para el "modificar datos"
			System.out.println("ID : - " + executionHijo.getId());
				
				 List<Object[]> rta = null;
				 Query q = hibSession.getNamedQuery("sql_copiarObservacionesModificacion");
				 q.setString("ProcesoPadre", executionID);
				 q.setString("ProcesoHijo", executionHijo.getId());
				 rta = q.list();			
					*/		
				/* /SEBA */
			//}
			/** 
			 * Corto y copio las observaciones
			 */
			
			List<Observaciones> observaciones = hibSession.createQuery("from Observaciones where ObsExecutionId = '" + executionID + "'").list();
			Observaciones obs;
			for (int i=0; i<observaciones.size(); i++) {
				obs = observaciones.get(i);
				obs.setObsExecutionId(exId);
				hibSession.save(obs);
			}
			
			hibSession.getTransaction().commit();
		}
		catch (HibernateException e) {
			if (hibSession.getTransaction() != null)
				if (hibSession.getTransaction().isActive())
					hibSession.getTransaction().rollback();
			e.printStackTrace();
			throw new GuardarParametrosException(); 
		}
		catch (Exception e) {
			if (hibSession.getTransaction() != null)
				if (hibSession.getTransaction().isActive())
					hibSession.getTransaction().rollback();
			e.printStackTrace();
			throw new GuardarParametrosException();
		}
	}
	
	public void setProcessEngine(ProcessEngine pe) {
		processEngine = pe;
	}
	
	public void setExecutionService(ExecutionService es) {
		executionService = es;
	}
	
	@Override
	public void execute(ExecutionService execution, String taskID, String usuario, String executionID) throws GuardarParametrosException {
		executionService = execution;
		this.execute(taskID, usuario, executionID);
	}
}
